package com.hainiu.cat.interview.juc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * create by biji.zhao on 2021/7/2
 */
public class CountDownLatchTest {

    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(2);
        System.out.println("主线程开始执行…… ……");
        //第一个子线程执行
        ExecutorService es1 = Executors.newSingleThreadExecutor();
        es1.execute(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("子线程："+Thread.currentThread().getName()+"执行");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            latch.countDown();
        });
        es1.shutdown();

        //第二个子线程执行
        ExecutorService es2 = Executors.newSingleThreadExecutor();
        es2.execute(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("子线程："+Thread.currentThread().getName()+"执行");
            latch.countDown();
        });
        es2.shutdown();
        System.out.println("等待两个线程执行完毕…… ……");
        // 等待两个线程执行完毕
        latch.await();
    }


    private static void testLatch() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);
        new Thread(new FutureTask<>(() -> {
            latch.countDown();
            return Thread.currentThread().getName();
        }), "A").start();
        new Thread(new FutureTask<>(() -> {
            latch.countDown();
            return Thread.currentThread().getName();
        }), "B").start();
        // 等待两个线程执行完毕
        latch.await();
    }
}
